// packageJ/levelCompel/levelCompel.js
const app = getApp();
const skinBehavior = require('../../utils/themeSkin/skinBehavior');
Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    pickerValue: [0, 0, 0],
    // 添加商品
    show: false,
    // 邀请码确认
    show1: false,
    show2: false,
    // 客服弹窗显隐
    kefuShow: false,
    // 协议开关
    agreement: false,
    addressName: "",
    stree: "",
    Userinfo: {},
    // 邀请码
    invite_code: "",
    // 新客下单设置
    settingInfo: {},
    // 客服
    cservice: "",
    service_mobile: "",
    service_QRcode: "",
    goods: [],
    nickname: "",
    mobile: "",
    detailAddress: "",
    openPlatformAgreement: false,
    popoverProtocolContent_title: "用户协议",
    popoverProtocolContent_content: "",
    province: "",
    city: "",
    district_q: "",

    page: 1,
    isLoadMore: true,
    total_page: 0,
    keyword: "",
    listData: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getUserinfo();
    this.getData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  closeTap(e) {
    let kye = e.currentTarget.dataset.key;
    this.setData({
      [kye]: !this.data[kye]
    })
  },
  streetConfirm(e) {
    console.log(e)
    this.setData({
      stree: e.currentTarget.dataset.item.areaname,
      streetShow: false
    })
  },
  streetChoose() {
    this.setData({
      streetShow: true
    })
  },
  closePop() {
    this.setData({
      kefuShow: false,
    });
  },
  agreementTap_popup() {
    this.setData({
      openPlatformAgreement: true
    })
  },
  chooseGood(e) {
    if(this.data.goods.length > 0){
      this.setData({
        goods:[]
      })
    }
    let item = e.currentTarget.dataset.item;
    let goodInfo = {
      goods_id: item.id,
      total: 1,
      option_id: 0
    };
    // let status = true;
    // this.data.goods.forEach((element, ind) => {
    //   if (element.goods_id != item.id) {
    //     status = true;
    //   } else {
    //     status = false;
    //     this.data.goods.splice(ind, 1)
    //   }
    // });
    // if (status) {
      this.data.goods.push(goodInfo);
    // }
    this.setData({
      goods: this.data.goods,
      chooseGoodArr : item,
    })
  },
  deleteMethod(e) {
    this.setData({
      chooseGoodArr:'',
      goods:[]
    })
  },
  submitOrder() {
    if(this.data.goods.length <= 0){
      app.tips('请选择下单商品')
      return
    }
    if (this.data.settingInfo.treaty_switch && !this.data.agreement) {
      app.tips("请勾选用户协议");
      return;
    }
    if (app._isTextEmpty(this.data.nickname)) {
      app.tips("请输入收件人姓名");
      return;
    }
    if (app._isTextEmpty(this.data.mobile)) {
      app.tips("请输入收货号码");
      return;
    }
    if (app._isTextEmpty(this.data.addressName)) {
      app.tips("请选择所在地区");
      return;
    }
    if(this.data.strShow){
      if (app._isTextEmpty(this.data.stree)) {
        app.tips("请选择所在街道");
        return;
      }
    }
    

    if (app._isTextEmpty(this.data.detailAddress)) {
      app.tips("请输入详细地址");
      return;
    }
    let currentAddress = {
      province: this.data.province,
      city: this.data.city,
      district: this.data.district_q,
      street: this.data.stree,
      address: this.data.detailAddress,
      mobile: this.data.mobile,
      username: this.data.nickname
    };
    let json = {
      address: encodeURIComponent(JSON.stringify(currentAddress)),
      dispatch_type_id: 1,
      goods: JSON.stringify(this.data.goods),
      member_coupon_ids: "",
      orders: ""
    };
    let urlStr = app.getNetAddresss("order.create");
    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          wx.redirectTo({
            url: "/packageD/buy/orderPay/orderPay?order_id=" + res.data.order_ids + "&status=2",
          });
        } else {
          app.tips(res.msg);
        }
      }
    });
  },

  addGoddInit() {
    this.setData({
      page: 1,
      total_page: 0,
      isLoadMore: true,
      listData: []
    })
  },
  addGoodMethod() {
    this.addGoddInit();
    let urlStr = app.getNetAddresss("plugin.level-compel.frontend.controllers.goods.index");
    app._getNetWork({
      url: urlStr,
      data: {
        keyword: this.data.keyword,
        page: this.data.page
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.data.isLoadMore = true;
          this.setData({
            total_page: res.data.last_page ? res.data.last_page : 0,
            listData: res.data.data,
            show: true
          })
        } else {
          app.tips(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  addGoodMethodMore() {
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      this.setData({
        page: this.data.page + 1
      })
      urlStr = app.getNetAddresss('plugin.level-compel.frontend.controllers.goods.index');
      app._postNetWork({
        url: urlStr,
        data: {
          keyword: this.data.keyword,
          page: this.data.page
        },
        success: (resdata) => {
          let res = resdata.data
          if (res.result == 1) {
            this.data.isLoadMore = true;
            this.setData({
              listData: this.data.listData.concat(res.data.data),
            })
          } else {
            this.data.page = this.data.page - 1;
            this.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  getUserinfo() {
    let urlStr = app.getNetAddresss("member.member.getUserInfo");
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            Userinfo: res.data
          })
        } else {
          app.tips(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  toPay(e){
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageD/buy/orderPay/orderPay?order_id='+id,
    })
  },
  getData() {
    let urlStr = app.getNetAddresss("plugin.level-compel.frontend.controllers.page.index");
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            settingInfo: res.data,
            orderSet:res.data.order,
            cservice: res.data.customer_service.cservice,
            service_mobile: res.data.customer_service.service_mobile ? res.data.customer_service.service_mobile : "",
            service_QRcode: res.data.customer_service.service_QRcode ? res.data.customer_service.service_QRcode : "",
            agreement: res.data.treaty_tick,
            popoverProtocolContent_title: res.data.treaty_title,
            popoverProtocolContent_content: res.data.treaty_content,
          })
          if (res.data.is_inviter == 0) {
            this.setData({
              show1: true
            })
          }
        } else {
          app.tips(res.msg);
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  edit() {
    if (this.data.show1) {
      this.data.show1 = false;
      this.data.show2 = true;
    } else {
      this.data.show1 = true;
      this.data.show2 = false;
    }
    this.setData({
      show1: this.data.show1,
      show2: this.data.show2
    })
  },
  confirm() {
    let urlStr = app.getNetAddresss("member.member.update-member-invite");
    app._getNetWork({
      url: urlStr,
      data: {
        parent_id: this.data.Userinfo.yz_member.parent_id
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            show1: false
          })
        } else {
          app.tips(res.msg);
        }
      }
    });
  },
  submit() {
    if (app._isTextEmpty(this.data.invite_code)) {
      app.tips('请输入邀请码')
      return;
    }
    let urlStr = app.getNetAddresss("member.member.refuseGoods");
    app._getNetWork({
      url: urlStr,
      data: {
        invite_code: this.data.invite_code
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            show2: false
          })
        } else {
          app.tips(res.msg);
        }
      }
    });
  },
  closeAgreement() {
    this.setData({
      openPlatformAgreement: false
    })
  },
  //打开地址选择器
  openDateLwtbtn: function () {
    this.setData({
      openDateLw: true
    });
    this._initAddressInfo();
  },
  // 关闭选择收货地址
  _closeDateLw: function () {
    this.setData({
      openDateLw: false
    });
  },
  // 确定选择收货地址
  _okAddress: function () {
    let seleData = this.data.selectAddressData;
    this.setData({
      "addressName": seleData[0].name + ' ' + seleData[1].name + ' ' + seleData[2].name,
      province: seleData[0].name,
      city: seleData[1].name,
      district_q: seleData[2].name
    });
    this._getStreet(seleData[2].id);
    this._closeDateLw();
  },
  //获取街道
  _getStreet(param, key = '') {
    let that = this;
    let urlStr = app.getNetAddresss("member.memberAddress.street");
    urlStr += "&district_id=" + param;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1 && !app._isTextEmpty(res.data)) {
          if (!app._isTextEmpty(res.data) && res.data.length > 0) {
            that.setData({
              districtVal: res.data,
              strShow: true
            });
            if (key) {
              that.setData({
                street: key
              })
            }
          } else {
            that.setData({
              strShow: false
            });
          }
        } else {
          that.setData({
            strShow: false
          });
        }
      },
      fail: function (res) {
        that.setData({
          strShow: false
        });
        console.log(res);
      }
    });
  },
  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2]
    });
    this._initAddressInfo();
  },
  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地址信息准备就绪");
        that._getProvinceData();
      },
      fail: function (res) {
        console.log("省fail");
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: 'provinceData',
              data: province
            });
            wx.setStorage({
              key: 'cityData',
              data: city
            });
            wx.setStorage({
              key: 'districtData',
              data: district
            });
            that._initAddressInfo();
          },
          fail: function (res) {},
          state: true
        });
      }
    });
  },
  // 读取省key
  _getProvinceData: function () {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        // console.log("省读取成功", res.data);
        that.setData({
          provinceData: res.data
        });
        that.setData({
          "selectAddressData[0].name": res.data[that.data.pickerValue[0]].areaname,
          "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
          "selectAddressData[0].index": that.data.pickerValue[0]
        });
        that._getCityData();
      }
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function () {
    var _data = this.data.selectAddressData[0];
    // console.log("城市", "_data", _data);
    var that = this;
    var _keyName = 'cityData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        // console.log("城市读取成功", res);

        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        // console.log("城市数据筛选", _json);
        that.setData({
          cityData: _json
        });
        that.setData({
          "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
          "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
          "selectAddressData[1].index": that.data.pickerValue[1]
        });
        that._getDistrictData();
      }
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    // console.log("地区", "_data", _data)
    var that = this;
    var _keyName = 'districtData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地区读取成功");
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        // console.log("地区数据筛选", _json);
        that.setData({
          districtData: _json
        });
        // console.log("districtData", _json);
        that.setData({
          "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
          "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
          "selectAddressData[2].index": that.data.pickerValue[2]
        });
        // console.log("over", that.data.selectAddressData);
      }
    });
  },
})